import axios from 'axios';

const state = {
  productItems: []
}


const mutations = {
  //更新products
  UPDATE_PRODUCT_ITEMS(state, payload) {
    state.productItems = payload;
  }
};

const actions = {
  //获取products
  /*完全方法
  getProductItems (context) {
    // action goes here
  }*/
  //通过es6 destructore
  getProductItems({ commit }) {
    axios.get('/api/products?token=D6W69PRgCoDKgHZGJmRUNA').then((response) => {
      commit('UPDATE_PRODUCT_ITEMS', response.data)
    });
  },
  addCartItem({ commit }, cartItem) {
    return axios.post('/api/cart', cartItem).then((response) => {
      commit('UPDATE_CART_ITEMS', response.data)
    });
  },

};

const getters = {
  productItems: state => state.productItems,
  productItemFromId: (state) => (id) => {
    return state.productItems.find(productItem => productItem.id === id)
  }

}

const productModule = {
  state,
  mutations,
  actions,
  getters
}

export default productModule;

